package com.mobilekites.downloader;

import java.io.File;

import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.widget.Toast;
import com.mobilekites.R;

public interface PhotoDownloader {
	public static final String FOLDER = "HaiVL_MobileKites";

	public void startDownload(String url);

	public static class PhotoDownloaderImpl implements PhotoDownloader {
		DownloadManager mDownloadManager;
		Context mContext;

		@TargetApi(Build.VERSION_CODES.GINGERBREAD)
		public PhotoDownloaderImpl(Context context) {
			mDownloadManager = (DownloadManager) context
					.getSystemService(Context.DOWNLOAD_SERVICE);
			mContext = context;
		}

		@SuppressWarnings("deprecation")
		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		@Override
		public void startDownload(String url) {
			Request request = new Request(Uri.parse(url));
			request.setMimeType("image/jpeg");
			File file = new File(Environment.getExternalStorageDirectory(),
					PhotoDownloader.FOLDER);
			if (!file.exists())
				file.mkdirs();
			request.setDestinationUri(Uri.fromFile(file));
			request.setDestinationInExternalPublicDir(PhotoDownloader.FOLDER,
					String.format(System.currentTimeMillis() + ".%s", "jpg"));
			if (Build.VERSION.SDK_INT >= 11) {
				request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
			} else {
				request.setVisibleInDownloadsUi(true);
				request.setShowRunningNotification(true);
			}
			mDownloadManager.enqueue(request);
			Toast.makeText(mContext, R.string.kites_start_download,
					Toast.LENGTH_LONG).show();
		}
	}
}
